<template>
    <ul class="pagination pagination-md pull-right no-margin">
        <li><a @click="prePage()">上一页</a></li>
        <li :class="{active:1 == currentPage}"><a @click="goPage(1)">1</a></li>
        <li v-if="currentPage > 4"><a>...</a></li>
        <li v-for="page in pages" :class="{active:page == currentPage}"><a @click="goPage(page)">{{page}}</a></li>
        <li v-if="currentPage < totalPage-3"><a>...</a></li>
        <li :class="{active:totalPage == currentPage}"><a @click="goPage(totalPage)">{{totalPage}}</a></li>
        <li><a @click="nextPage()">下一页</a></li>
    </ul>
</template>

<script>
export default {
    props: {
        totalPage: { // 总页数
            type: Number,
            default: 1,
            required: true
        },
        initPage: {
            type: Number,
            default: 1
        }
    },
    data() {
        return {
            currentPage:this.initPage
        }
    },
    methods: {
        goPage(page) {
            this.currentPage = page;
            this.$emit('go-page',{page:this.currentPage});
            var origQuery = {
                ...this.$route.query,
            };
            origQuery.page = page;
            this.$router.push({path:this.$route.path,query:origQuery});
        },
        prePage(){
            if(this.currentPage == 1){
                return;
            }
            this.goPage(this.currentPage-1);
        },
        nextPage(){
            if(this.currentPage == this.totalPage){
                return;
            }
            this.goPage(this.currentPage+1);
        },
    },
    watch:{
        initPage(newVal){
            this.currentPage = newVal;
        }
    },
    computed: {
        pages() {
            var start = 2;
            var offset = 7;
            if(this.totalPage > 4){
                if(this.currentPage > 4 && this.currentPage <= (this.totalPage - 3)){
                    start = this.currentPage - 3;
                }
                if(this.currentPage > this.totalPage - 3){
                    start = this.totalPage - 6;
                }
            }

            var pages = new Array();
            for(var i=1;i<=offset;i++){
                var num = start+(i-1);
                if(num > this.totalPage-1){
                    break;
                }
                pages.push(num);
            }
            return pages;
        }
    }
};
</script>
<style>
.pagination a{
    cursor:pointer;
}
</style>
